package com.zq.server.api.service.impl;


import java.io.IOException;
import java.net.BindException;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import com.google.gson.Gson;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import com.zq.common.config.Properties.QiNiuYunProperties;
import com.zq.common.exception.base.BaseException;
import com.zq.common.utils.file.FileUploadUtils;
import com.zq.common.utils.file.MimeTypeUtils;
import com.zq.server.api.service.ApiFileService;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class ApiFileServiceImpl implements ApiFileService {

    @Autowired
    private QiNiuYunProperties qiNiuYunProperties;


    /**
     * 上传文件
     *
     * @param
     * @return
     */
    @Override
    @Transactional(rollbackFor = BaseException.class)
    public String uploadFile(MultipartFile file) throws IOException {
        Configuration cfg = new Configuration(Region.region2());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
        UploadManager uploadManager = new UploadManager(cfg);
        Auth auth = Auth.create(qiNiuYunProperties.getAccessKey(), qiNiuYunProperties.getSecretKey());
        String upToken = auth.uploadToken(qiNiuYunProperties.getBucket());
        //文件
        Map<String,String> imageLocalPath = FileUploadUtils.upload(file, MimeTypeUtils.IMAGE_EXTENSION, qiNiuYunProperties.getLocalPath());
        String path = imageLocalPath.get("path");
        Response response = uploadManager.put(path,imageLocalPath.get("fileName"), upToken);
        //解析上传成功的结果
        DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
        String publicUrl = String.format("%s/%s", qiNiuYunProperties.getPublicUrl(), putRet.key);
        Boolean isDeleteResult = FileUploadUtils.deleteFile(path);
        if (isDeleteResult){
            return publicUrl;
        }else{
           throw new BindException("File upload Error: " + publicUrl);
        }
    }
}
